<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Project;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;

class ProjectController extends Controller
{
    public function save(Request $request){
        $id = $request->input("id");
        $name = $request->input("name");
        $companyName = $request->input("companyName");
        $businessLicenseImage = $request->input("businessLicenseImage");
        $wonerIdcardImage = $request->input("wonerIdcardImage");
        $wonerCreditImage = $request->input("wonerCreditImage");
        $userIdcardImage = $request->input("userIdcardImage");
        $userCreditImage = $request->input("userCreditImage");
        $otherFileUrl = $request->input("otherFileUrl");

        $model = Project::query()->find($id);
        if(empty($model)){
            $model = new Project;
            $model->project_no = "XM".date("YmdHis").rand(1000,9999);
        }
        $model->name = $name;
        $model->company_name = $companyName;
        $model->business_license_image = $businessLicenseImage;
        $model->woner_idcard_image = $wonerIdcardImage;
        $model->woner_credit_image = $wonerCreditImage;
        $model->user_idcard_image = $userIdcardImage;
        $model->user_credit_image = $userCreditImage;
        $model->other_file_url = $otherFileUrl;
        $model->save();
        return $this->httpSuccess();
    }

    public function pageItems(Request $request){
        $projectNo = $request->input("projectNo","");
        $name = $request->input("name","");
        $createdAtLeft = $request->input("createdAtLeft","");
        $createdAtRight = $request->input("createdAtRight","");
        $page = $request->input("page",1);
        $pageSize = $request->input("pageSize",20);
        $paginate = Project::query()
            ->when($projectNo, function (Builder $query)use($projectNo) {
                $query->where("project_no",$projectNo);
            })
            ->when($name, function (Builder $query)use($name) {
                $query->where("name",$name);
            })
            ->when($createdAtLeft, function (Builder $query)use($createdAtLeft) {
                $query->where("created_at",">=",$createdAtLeft);
            })
            ->when($createdAtRight, function (Builder $query)use($createdAtRight) {
                $query->where("created_at","<=",$createdAtRight);
            })
            ->select("*")
            ->orderByDesc("id")
            ->paginate($pageSize,['*'],'page',$page);
        return $this->httpSuccess([
            "total"=>$paginate->total(),
            "items"=>$paginate->items(),
        ]);

    }

    public function updateStatus(Request $request){
        $status = $request->input("status");
        $ids = $request->input("ids",[]);
        Project::query()->whereIn("id",$ids)->update(["status"=>$status]);
        return $this->httpSuccess();
    }
}
